from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.order.models import OrderInfo
from apps.payment.models import Payment
from meiduo_mall import settings
from utils.response_code import RETCODE


class AlipayView(View):
    def get(self,request,order_id):
        try:
            order=OrderInfo.objects.get(order_id=order_id,user=request.user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.JsonResponse({'code':RETCODE.NODATAERR})
        # 1.创建alipay实例
        from alipay import AliPay

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.DEBUG  # 默认False
        )
        # 2.调用网站支付方法(接口),生成order_string
        # 如果你是 Python 3的用户，使用默认的字符串即可
        subject = "测试订单"

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,

        )
        # 3.拼接支付的url
        # pay_url = 'https://openapi.alipay.com/gateway.do?'  # 线上的
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string  # 测试的
        # 4.返回这个url
        return http.JsonResponse({'code': RETCODE.OK, 'alipay_url': pay_url})


class PaymentStatusVIew(View):
    def get(self,request):
        # 1.创建alipay实例
        from alipay import AliPay

        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.DEBUG  # 默认False
        )
        # 2.根据验证方法判断支付是否真的成功了
        # 在这里保存支付宝交易流水号和订单id
        # for django users
        data = request.GET.dict()

        signature = data.pop("sign")

        # verification
        success = alipay.verify(data, signature)
        if success:
            # 成功则保存
            out_trade_no = data.get('out_trade_no')
            trade_no = data.get('trade_no')

            Payment.objects.create(
                # order=OrderInfo.objects.get(order_id=out_trade_no),
                order_id=out_trade_no,
                trade_id=trade_no
            )

            # 修改订单的状态
            OrderInfo.objects.filter(order_id=out_trade_no).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])

        return render(request, 'pay_success.html', context={'trade_id': trade_no})
